package com.company.ThreadLearn;

public class Synchronized {
    final static int LOOP = 1000;
    public static int count = 0;
    public Synchronized() throws InterruptedException {
        Counter c = new Counter();
        Thread t1 = new ADDT(c);
        Thread t2 = new DECT(c);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(c.get());
    }
}

class Counter{
    int count = Synchronized.count;
    public void add(int n){
        synchronized(this){count+=n;}
    }
    public void dec(int n){
        synchronized (this){count-=n;}
    }
    public int get(){
        return count;
    }
}
class ADDT extends Thread{
    Counter c;
    public ADDT(Counter c) {
        this.c = c;
    }
    public void run(){
        for (int i = 0;i < Synchronized.LOOP;i++){
            c.add(i);
        }
    }
}

class DECT extends Thread{
    Counter c;
    public DECT(Counter c) {
        this.c = c;
    }
    public void run(){
        for (int i = 0;i < Synchronized.LOOP;i++){
            c.dec(i);
        }
    }
}
